package com.example.linearlayoutdemo.network.fun.network;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit 单例管理（全局复用，避免重复创建）
 */
public class RetrofitClient {
    // 服务器基础 URL（替换为实际项目地址）
    private static final String BASE_URL = "https://reqres.in";
    private static Retrofit retrofit;

    // 单例模式：获取 Retrofit 实例
    public static Retrofit getInstance() {
        if (retrofit == null) {
            // 1. 配置 OkHttp（添加日志拦截器，调试用）
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // 打印完整请求/响应

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new GlobalHeaderInterceptor())
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(10, TimeUnit.SECONDS) // 连接超时
                    .readTimeout(15, TimeUnit.SECONDS)    // 读取超时
                    .build();

            // 2. 初始化 Retrofit（绑定 OkHttp + Gson 解析）
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create()) // Gson 自动解析 JSON
                    .build();
        }
        return retrofit;
    }

    // 获取 API 接口实例（全局调用）
    public static ApiFunService getApiService() {
        return getInstance().create(ApiFunService.class);
    }
}
